package com.wutongyu.mannyburger;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class SecurityQuestionFragment extends Fragment {

    private static final String TAG = "SecurityQuestionFrag";
    private static final String ARG_PHONE = "arg_phone";
    private static final String ARG_QUESTION_ID = "arg_question_id";

    private TextView textViewSecurityQuestion;
    private EditText editTextSecurityAnswer;
    private Button buttonVerify;
    private UserDatabaseHelper dbHelper;

    private String phone;
    private int questionId;

    /**
     * 使用工厂方法创建新实例
     */
    public static SecurityQuestionFragment newInstance(String phone, int questionId) {
        SecurityQuestionFragment fragment = new SecurityQuestionFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PHONE, phone);
        args.putInt(ARG_QUESTION_ID, questionId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            phone = getArguments().getString(ARG_PHONE);
            questionId = getArguments().getInt(ARG_QUESTION_ID);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_security_question, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        textViewSecurityQuestion = view.findViewById(R.id.text_view_security_question);
        editTextSecurityAnswer = view.findViewById(R.id.edit_text_security_answer);
        buttonVerify = view.findViewById(R.id.button_verify);

        dbHelper = new UserDatabaseHelper(requireContext());

        // 显示密保问题
        setSecurityQuestion();

        buttonVerify.setOnClickListener(v -> verifySecurityAnswer());
    }

    private void setSecurityQuestion() {
        // 从字符串资源数组中获取密保问题
        String[] securityQuestions = getResources().getStringArray(R.array.security_questions);
        
        // 确保问题ID在有效范围内
        if (questionId >= 0 && questionId < securityQuestions.length) {
            textViewSecurityQuestion.setText(securityQuestions[questionId]);
        } else {
            // 处理无效的问题ID
            textViewSecurityQuestion.setText("未知问题");
            Log.e(TAG, "无效的密保问题ID: " + questionId);
        }
    }

    private void verifySecurityAnswer() {
        String answer = editTextSecurityAnswer.getText().toString().trim();

        // 基本验证
        if (TextUtils.isEmpty(answer)) {
            editTextSecurityAnswer.setError("答案不能为空");
            editTextSecurityAnswer.requestFocus();
            return;
        }

        // 验证密保答案
        if (dbHelper.checkSecurityAnswer(phone, answer)) {
            // 验证成功，导航到重置密码页面
            navigateToResetPassword(phone);
        } else {
            // 验证失败
            Toast.makeText(getContext(), "密保答案不正确", Toast.LENGTH_SHORT).show();
            Log.w(TAG, "密保答案验证失败: " + phone);
        }
    }

    private void navigateToResetPassword(String phone) {
        ResetPasswordFragment fragment = ResetPasswordFragment.newInstance(phone);
        
        // 跳转到重置密码页面
        FragmentManager fragmentManager = getParentFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.nav_host_fragment_container, fragment);
        transaction.addToBackStack(null); // 允许用户按返回键回到上一个页面
        transaction.commit();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 关闭数据库连接
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
} 